<?php
/**
 * Created by PhpStorm.
 * User: jaylen
 * Date: 2020-04-18
 * Time: 16:43
 */

namespace app\common\model;


use app\common\exception\ParameterException;
use app\common\exception\UploadException;
use think\model\concern\SoftDelete;
use app\common\validate\Atlas as Validate;

class Atlas extends BaseModel
{
    protected $hidden = ['create_time','update_time','delete_time'];

    // 使用软删除
    use SoftDelete;
    protected $deleteTime = 'delete_time';

    // 添加带有域名前缀的图片地址字段
    public function getImgUrlAttr($value, $data)
    {
        return $this->prefixImgUrl($data['img_path']);
    }

    /**
     * 获取图集的文件列表
     * @param array $params
     * @return Atlas|\think\Paginator
     */
    public static function getImageList(array $params = [])
    {
        static::validatePaginationData($params);

        $static = new static();

        if (isset($params['category_id'])) {
            switch ($params['category_id']) {
                case '-1':
                    break;
                default :
                    $static = $static->where('category_id','=', intval($params['category_id']));
            }
        }

        $static = $static->field(['id','name','img_path'])
            ->order(['create_time'=>'desc'])
            ->append(['img_url'])
            ->paginate([
                'page' => $params['page'],
                'list_rows' => $params['limit']
            ], false);

        return $static;
    }

    /**
     * 往数据库中插入图集的图片数据
     * @param array $data
     * @param $category_id
     * @return array|bool
     */
    public static function addImage(array $data, $category_id)
    {
        $static = new static();

        //判断data中的name字段是否为数组
        if (isset($data['origin_name']) && is_array($data['origin_name'])) {
            $insert_data = [];
            foreach ($data['origin_name'] as $key => $value) {
                $insert_data[$key]['name'] = $value;
                $insert_data[$key]['img_path'] = $data['save_path'][$key];
                $insert_data[$key]['md5'] = $data['md5'][$key];
                $insert_data[$key]['type'] = 1;
                $insert_data[$key]['category_id'] = $category_id;
            }

            $result = $static->allowField(['name','img_path','md5','type','category_id'])
                ->saveAll($insert_data);

            if ($result->isEmpty()) {
                return false;
            } else {
                return $result->append(['img_url'])
                    ->toArray();
            }

        } else {
            $result = $static->allowField(['name','img_path','md5','type','category_id'])
                ->save([
                    'name' => $data['origin_name'],
                    'img_path' => $data['save_path'],
                    'md5' => $data['md5'],
                    'type' => 1,
                    'category_id' => $category_id
                ]);

            if (!$result) {
                return false;
            } else {
                return [
                    'id' => $static->id,
                    'name' => $static->getAttr('name'),
                    'img_path' => $static->img_path,
                    'img_url' => $static->prefixImgUrl($static->img_path),
                    'category_id' => $category_id
                ];
            }
        }
    }

    /**
     * 修改图集对应的栏目
     * @param array $data
     * @return bool
     */
    public static function changeCategory(array $data)
    {
        $validate = new Validate();
        if (!$validate->scene('change_category')->check($data)) {
            throw new ParameterException([
                'msg' => $validate->getError()
            ]);
        }

        // 根据id获取当前图片的相关信息
        $static = static::find($data['id']);

        if (empty($static)) {
            throw new UploadException([
                'msg' => '图集中找不到该图片',
                'errorCode' => 10007
            ]);
        }

        if (self::checkImageExtra($static->getAttr('name'), $static->getAttr('md5'), $data['category_id'])) {
            throw new UploadException();
        }

        $result = $static->allowField(['id','category_id'])
            ->save($data);

        if ($result !== false) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 检查图片是否存在
     * @param $name 图片名称
     * @param $md5 图片对应的md5值
     * @param $category_id
     * @return bool
     */
    public static function checkImageExtra($name, $md5, $category_id)
    {
        $data = static::where([
            ['name','=',$name],
            ['md5','=',$md5],
            ['category_id','=',$category_id]
        ])->find();

        if (!$data) {
            return false;
        } else {
            return true;
        }
    }



}